import { onMounted, onUnmounted, reactive, ref } from "vue";

type Options = {
  key1: string;
  key2: string;
  onAllPress: () => void;
};

const useKeysPress = ({ key1, key2, onAllPress }: Options) => {
  const abort = ref(new AbortController());
  const keysDownCount = reactive({ key1: 0, key2: 0 });

  const handleKeyDown = (e: KeyboardEvent) => {
    switch (e.key) {
      case key1:
        keysDownCount.key1++;
        break;
      case key2:
        keysDownCount.key2++;
        break;
    }

    if (keysDownCount.key1 === 1 && keysDownCount.key2 === 1) {
      onAllPress();
    }
  };

  const handleKeyUp = (e: KeyboardEvent) => {
    switch (e.key) {
      case key1:
        keysDownCount.key1 = 0;
        break;
      case key2:
        keysDownCount.key2 = 0;
        break;
    }
  };

  onMounted(() => {
    const opts = () => ({ signal: abort.value.signal });
    window.addEventListener("keydown", handleKeyDown, opts());
    window.addEventListener("keyup", handleKeyUp, opts());
  });

  onUnmounted(() => {
    abort.value.abort();
  });

  return { key1, key2 };
};

export default useKeysPress;
